package com.sdx.console.content.web;

import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Date;
import java.util.Collections;

import javax.servlet.http.HttpServletResponse;

import com.fasterxml.jackson.core.JsonProcessingException;
import com.sdx.common.entity.ResCloudFile;
import com.sdx.common.service.ResCloudFileService;
import com.sdx.common.utils.JacksonUtils;
import com.sdx.service.ConfigService;
import com.sdx.third.AliOSSApi;
import org.apache.commons.lang3.StringUtils;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.beetl.sql.core.engine.PageQuery;
import org.jxls.common.Context;
import org.jxls.reader.ReaderBuilder;
import org.jxls.reader.ReaderConfig;
import org.jxls.reader.XLSReadMessage;
import org.jxls.reader.XLSReadStatus;
import org.jxls.reader.XLSReader;
import org.jxls.util.JxlsHelper;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.servlet.ModelAndView;

import com.ibeetl.admin.console.web.dto.DictExcelImportData;
import com.ibeetl.admin.console.web.query.UserQuery;
import com.ibeetl.admin.core.annotation.Function;
import com.ibeetl.admin.core.annotation.Query;
import com.ibeetl.admin.core.entity.CoreDict;
import com.ibeetl.admin.core.entity.CoreUser;
import com.ibeetl.admin.core.web.JsonResult;
import com.ibeetl.admin.core.web.JsonReturnCode;
import com.ibeetl.admin.core.util.*;
import com.sdx.common.utils.*;
import com.sdx.console.content.entity.*;
import com.sdx.console.content.service.*;
import com.sdx.console.content.web.query.*;
import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import com.ibeetl.admin.core.web.AuthorizedBaesController;


/**
 * EbookUpdateRecord 接口
 */
@RequestMapping("/content/ebookUpdateRecord")
@Controller
public class EbookUpdateRecordController extends AuthorizedBaesController{
	private static final Logger log = LoggerFactory.getLogger(EbookUpdateRecordController.class);
    private static final String MODEL = "/content/ebookUpdateRecord";


    @Resource
	private EbookUpdateRecordService ebookUpdateRecordService;

    @Resource
    ResCloudFileService resCloudFileService;

	/**
	 * 初始化页面需要的列表数据，
	 *
	 */
	private void setPageParam(ModelAndView view,HttpServletRequest request,Integer bookId) {
        view.addObject("bookId", bookId);
	}

    /* 页面 */

    @GetMapping("/index.do")
    @Function("content.ebookUpdateRecord.query")
    @ResponseBody
    public ModelAndView index(HttpServletRequest request,Integer bookId) {
        ModelAndView view = new ModelAndView(MODEL+"/index.html") ;
		setPageParam(view,request,bookId);
        return view;
    }

    @GetMapping("/edit.do")
    @Function("content.ebookUpdateRecord.edit")
    @ResponseBody
    public ModelAndView edit(HttpServletRequest request,Integer id) {
        ModelAndView view = new ModelAndView(MODEL+"/add.html");
        EbookUpdateRecord ebookUpdateRecord = ebookUpdateRecordService.queryById(id);
        view.addObject("ebookUpdateRecord", ebookUpdateRecord);
		setPageParam(view,request,ebookUpdateRecord.getBookId());
		try {
			view.addObject("ebookUpdateRecordJson", JacksonUtils.toJsonString(ebookUpdateRecord,JacksonUtils.DF1));
		} catch (JsonProcessingException e) {
			e.printStackTrace();
		}
        return view;
    }

    @GetMapping("/add.do")
    @Function("content.ebookUpdateRecord.add")
    @ResponseBody
    public ModelAndView add(HttpServletRequest request,Integer bookId) {
        ModelAndView view = new ModelAndView(MODEL+"/add.html");
		setPageParam(view,request,bookId);
        return view;
    }

    /* ajax json */

    @PostMapping("/list.json")
    @Function("content.ebookUpdateRecord.query")
    @ResponseBody
    public JsonResult<PageQuery> list(EbookUpdateRecord condtion)
    {
        PageQuery page = condtion.getPageQuery();
        ebookUpdateRecordService.queryByCondition(page);
        return JsonResult.success(page);
    }

    private JsonResult save(boolean isNew,EbookUpdateRecord ebookUpdateRecord,HttpServletRequest request
                            ,MultipartFile urlFile
	) {
    	JsonResult result = JsonResult.success();
		String dir = DateUtil.now("yyyyMMdd");
    	String subPath = "/file/ebook/update/"+ebookUpdateRecord.getBookId()+"/";
		String bucketName = "sdxpri";
		CoreUser user = getLoginUser(request);
        if (!FileUtils.isEmptyFile(urlFile)) {
            try{
                String coverFileNamePair = FileUtils.upload(subPath,urlFile);
                String coverStoreFile = coverFileNamePair.split("::")[0];
                coverStoreFile = subPath+coverStoreFile;
                AliOSSApi.uploadLocalFile(FileUtils.getRoot()+coverStoreFile,bucketName,coverStoreFile.substring(1));
                String coverUrl = "https://sdxpri."+ ConfigService.ossDomain+coverStoreFile;
                ebookUpdateRecord.setUrl(coverUrl);
                resCloudFileService.insertResFile(ResCloudFile.ALI,coverStoreFile,coverUrl,"f","章节地址");
            }catch(Exception e) {
                e.printStackTrace();
                result.setCode(JsonReturnCode.IO_ERROR.getCode());
                result.setMsg(e.getMessage());
            }
        }
    	if (isNew) {
			ebookUpdateRecord.setCreatedBy(user.getId().intValue());
			ebookUpdateRecord.setCreatedName(user.getName());
			ebookUpdateRecord.setCreatedTime(new Date());
			ebookUpdateRecord.setUpdatedBy(user.getId().intValue());
			ebookUpdateRecord.setUpdatedName(user.getName());
			ebookUpdateRecord.setUpdatedTime(new Date());
			ebookUpdateRecordService.save(ebookUpdateRecord);
		} else {
			ebookUpdateRecord.setUpdatedBy(user.getId().intValue());
			ebookUpdateRecord.setUpdatedName(user.getName());
			ebookUpdateRecord.setUpdatedTime(new Date());
			ebookUpdateRecordService.updateTemplate(ebookUpdateRecord);
		}
		return result;
	}
    @PostMapping("/add.json")
    @Function("content.ebookUpdateRecord.add")
    @ResponseBody
    public JsonResult add(@Validated(ValidateConfig.ADD.class)EbookUpdateRecord ebookUpdateRecord,HttpServletRequest request
            ,@RequestParam("urlFile") MultipartFile urlFile
		)
    {

        return save(true,ebookUpdateRecord,request,urlFile
		);
    }

    @PostMapping("/update.json")
    @Function("content.ebookUpdateRecord.edit")
    @ResponseBody
    public JsonResult<String> update(@Validated(ValidateConfig.UPDATE.class)  EbookUpdateRecord ebookUpdateRecord
            ,HttpServletRequest request,@RequestParam("urlFile") MultipartFile urlFile
		) {
		return save(false,ebookUpdateRecord,request,urlFile
		);
    }



    @GetMapping("/view.json")
    @Function("content.ebookUpdateRecord.query")
    @ResponseBody
    public JsonResult<EbookUpdateRecord>queryInfo(Integer id) {
        EbookUpdateRecord ebookUpdateRecord = ebookUpdateRecordService.queryById( id);
        return  JsonResult.success(ebookUpdateRecord);
    }

    @PostMapping("/delete.json")
    @Function("content.ebookUpdateRecord.del")
    @ResponseBody
    public JsonResult delete(String ids) {
		List<String> idList = Utils.strToList(ids,",");
        ebookUpdateRecordService.batchDelEbookUpdateRecord(idList);
        return JsonResult.success();
    }


}
